//
//  MyCollectionVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/10/26.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "MyCollectionVC.h"
#import "MyCollectionHeaderView.h"
#import "MyCollectionCell.h"
#import "MyCollectionCenterCell.h"
#import "SettingTabVC.h"
#import "MyCollectVC.h"
#import "MyContactVC.h"
#import "MyReleaseVC.h"
#import "MyMessageTabVC.h"
#import "RealAuthenticationVC.h"
#import "MyShopTabVC.h"
#import "RealComplayAuthenticationTabVC.h"
#import "FeedBackTabVC.h"
#import <UShareUI/UShareUI.h>
#import "ShareView.h"
#import "UIView+TYAlertView.h"
#import "LogInOrOutVC.h"
#import "MainNavC.h"
#import "MyShopVC.h"
#import "MyCollectionIconModel.h"
#import "AboutVC.h"
@interface MyCollectionVC ()<UICollectionViewDelegateFlowLayout,MyCollectionHeaderViewDelegate,ShareViewDelegate,MyCollectionCellDelegate>
@property(nonatomic,strong) MyCollectionHeaderView *headertView;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) NSMutableArray *iconMuta;
@property(nonatomic,assign) BOOL selectedCell;
@end

@implementation MyCollectionVC
static NSString *identifierHeaderView = @"headerView";
static NSString *identifier = @"Cell";
static NSString *identifierCenter = @"MyCollectionCenterCell";
-(NSMutableArray *)iconMuta
{
    if (!_iconMuta) {
        _iconMuta = [NSMutableArray array];
    }
    return _iconMuta;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self reloadInternet];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:[ImageColorHelper createImageWithColor:kWhite] forBarMetrics:UIBarMetricsDefault];
}
//- (UIStatusBarStyle)preferredStatusBarStyle
//{
//    return UIStatusBarStyleLightContent; //返回白色
//}
//
//- (BOOL)prefersStatusBarHidden {
////    return YES;  //设置状态栏隐藏
//    return NO; //设置状态栏显示
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [AFHTTPSessionManager manager];
    self.collectionView.frame = CGRectMake(0, -kStatusBarHeight, kUIScreen.size.width, kUIScreen.size.height+kStatusBarHeight);
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyCollectionCell" bundle:nil] forCellWithReuseIdentifier:identifier];
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyCollectionCenterCell" bundle:nil] forCellWithReuseIdentifier:identifierCenter];
    self.collectionView.backgroundColor = kBg;
    [self reloadInternet];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenMyCollection:) name:@"checkTokenMyCollection" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenError:) name:@"checkTokenError" object:nil];

}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    XLog(@"y:%f",scrollView.contentOffset.y);
    CGFloat width = kUIScreen.size.width;
    CGFloat yOffset = scrollView.contentOffset.y;
    if (yOffset<-20) {
        CGFloat totalOffset = 280 + ABS(yOffset);
        XLog(@"totalOffset:%f",totalOffset);
        self.headertView.frame = CGRectMake(0, yOffset, width, totalOffset);
        self.headertView.headIV.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
        self.headertView.nameL.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
        self.headertView.certificationL.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
        self.headertView.markL.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
        self.headertView.bgIV.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
        self.headertView.settingBtn.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
        self.headertView.autoLogInBtn.transform = CGAffineTransformMakeTranslation(0, ABS(yOffset));
    }
}
-(void)reloadInternet
{
    self.urlString = [NSString stringWithFormat:@"%@/icon/selectMyIcon",kUrl];
    [self.manager POST:self.urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *date = [responseObject objectForKey:@"date"];
        for (NSDictionary *dict in date) {
            MyCollectionIconModel *model = [MyCollectionIconModel mj_objectWithKeyValues:dict];
            [self.iconMuta addObject:model];
        }
        [self.collectionView reloadData];
//        [self.headertView reloadInternet];
        self.headertView.reloadDate = [UserDefaultsHelper readAutoLogIn];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }else if(section == 1){
        return 1;
    }else {
        return 6;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0||indexPath.section == 2) {
        MyCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        cell.indexPath = indexPath;
        cell.iconMuta = self.iconMuta;
        cell.delegate = self;
        return cell;
        
    }else {
        MyCollectionCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierCenter forIndexPath:indexPath];
        return cell;
    }
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView = nil;
//    if (indexPath.section == 0) {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            [collectionView registerClass:[MyCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:identifierHeaderView];
            self.headertView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:identifierHeaderView forIndexPath:indexPath];
//            [self.headertView reloadInternet];
            self.headertView.delegate = self;
            reusableView = self.headertView;
            self.headertView.reloadDate = 1;
//            headertView.backgroundColor = kLabel16Color;
//             [self.headertView reloadInternet];
            return reusableView;
        }else {
            return reusableView;
        }
//
//    }else {
//        return nil;
//    }
}
#pragma mark-代理-设置
- (void)myCollectionHeaderView:(MyCollectionHeaderView *)myCollectionHeaderView withTag:(NSInteger)tag
{
     UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if (tag == 0) {
        SettingTabVC *settingVC = [[SettingTabVC alloc]init];
        settingVC.hidesBottomBarWhenPushed = YES;
        settingVC.returnBlockTouXiangVC = ^(NSString *accountNamed, UIImage *image,BOOL autoLogIn) {
            [self reloadInternet];
        };
        [self.navigationController pushViewController:settingVC animated:YES];
    }else {
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
            LogInOrOutVC *logVC = [[LogInOrOutVC alloc]init];
            MainNavC *mianNav = [[MainNavC alloc]initWithRootViewController:logVC];
            [viewController presentViewController:mianNav animated:YES completion:nil];
        }else {
            LogInOrOutVC *logVC = [[LogInOrOutVC alloc]init];
            MainNavC *mainNav = [[MainNavC alloc]initWithRootViewController:logVC];
            [self presentViewController:mainNav animated:YES completion:nil];
        }
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(200, 300);
    }else {
        return CGSizeMake(200, 0);
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake((kVWidth)/3, 110);
    }else if (indexPath.section == 1) {
        return CGSizeMake(kVWidth, 110);
    }else {
        return CGSizeMake((kVWidth)/3, 130);
    }
    
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if(section == 1){
        return UIEdgeInsetsMake(0, 0, 0.5, 0);//分别为上、左、下、右
    }else{
        return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
    }
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.indexPath = indexPath;
    if (indexPath.section == 2&&indexPath.row == 3) {
        FeedBackTabVC *vc = [[FeedBackTabVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 2&&indexPath.row == 4) {
        AboutVC *vc = [[AboutVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 2&&indexPath.row == 5) {
        ShareView *shareView = [ShareView createViewFromNib];
        shareView.delegate = self;
        shareView.frame = CGRectMake(0, 0, kUIScreen.size.width,  kUIScreen.size.width*387/750);
        TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:shareView preferredStyle:TYAlertControllerStyleActionSheet];
        alertController.backgoundTapDismissEnable = YES;
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
            [LogOutAccount presentOutAccount];
            [UIAlertViewWarningAccount showWarningAccount];
        }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
            [LogOutAccount presentOutAccount];
        }else {
            self.dict = @{
                          @"userId":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken],
                          };
            XLog(@"self.dict:%@",self.dict);
            [CustomeManager POSTCheckTokenWithURLIndex:7 parameters:self.dict success:^(NSDictionary *dict) {
                
            } failure:^(NSError *error) {
            }];
            
        }
    }
}
-(void)checkTokenMyCollection:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    XLog(@"self.indexPath.row:%ld",self.indexPath.row);
    XLog(@"self.indexPath.section:%ld",self.indexPath.section);
    NSString *message = [info.userInfo objectForKey:@"message"];
    NSDictionary *date = [dict objectForKey:@"date"];
    [UserDefaultsHelper saveType:@"" value:[date objectForKey:@"type"]];
    NSInteger status = [[info.userInfo objectForKey:@"status"] integerValue];
    XLog(@"type:%@",[UserDefaultsHelper readType]);
    if (status == 200) {
        if (self.indexPath.section == 0) {
            if (self.indexPath.row == 0) {
                MyCollectVC *myCollectionVC = [[MyCollectVC alloc]init];
                [self.navigationController pushViewController:myCollectionVC animated:YES];
            }else if (self.indexPath.row == 1) {
                XLog(@"myContactVC");
                MyContactVC *myContactVC = [[MyContactVC alloc]init];
                [self.navigationController pushViewController:myContactVC animated:YES];
            }else {
                MyReleaseVC *myContactVC = [[MyReleaseVC alloc]init];
                [self.navigationController pushViewController:myContactVC animated:YES];
                
            }
        }else if(self.indexPath.section == 2){
            if (self.indexPath.row == 0) {
                MyMessageTabVC *messageVC = [[MyMessageTabVC alloc]init];
                [self.navigationController pushViewController:messageVC animated:YES];
                
            }else if (self.indexPath.row == 1) {
                RealAuthenticationVC *realVC = [[RealAuthenticationVC alloc]init];
                if ([[UserDefaultsHelper readType] integerValue] == 2||[[UserDefaultsHelper readType] integerValue] == 3||[[UserDefaultsHelper readType] integerValue] == 4) {
                    realVC.title = @"企业实名认证";
                }else if ([[UserDefaultsHelper readType] integerValue] == 5||[[UserDefaultsHelper readType] integerValue] == 6||[[UserDefaultsHelper readType] integerValue] == 7) {
                    realVC.title = @"个人实名认证";
                }else {
                    realVC.title = @"实名认证";
                }
                [self.navigationController pushViewController:realVC animated:YES];
                
            }else if (self.indexPath.row == 2) {
                
                [self checkTokenMyShop];
                
                
            }
        }
    }
    
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)checkTokenError:(NSNotification *)info
{
    XLog(@"登录失败");
//    NSNotification *notification = [NSNotification notificationWithName:@"logInOut" object:nil];
//    [[NSNotificationCenter defaultCenter]postNotification:notification];
//    [LogOutAccount presentOutAccount];
//    [UIAlertViewWarningAccount showWarningAccount];
}
#pragma mark-设备登录检测
-(void)checkTokenMyShop
{
    
    self.dict = @{
                  @"userId":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken]
                  };
//    [CustomeManager POSTWithURLIndex:50 parameters:self.dict success:^(NSDictionary *dict) {
//
//    } failure:^(NSError *error) {
//
//    }];
    self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *dict = info.userInfo;
        XLog(@"checkTokenMyShop:%@",responseObject);
        /**
         date =     {
         createtime = "<null>";
         headimg = "http://www.qichangkeji.vip/upload/img/50398daf-4c43-4602-a1b2-601dceaba106.png";
         id = 12;
         nickname = "\U5566\U5566\U5566";
         password = "<null>";
         phone = 17621764088;
         type = 0;
         };
         message = "\U6210\U529f";
         status = 200;
         */
        
        NSDictionary *date =[responseObject objectForKey:@"date"];
        NSString *type = [date objectForKey:@"type"];
        [UserDefaultsHelper saveType:@"" value:type];
        XLog(@"type:%@",type);
        NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
        if (status == 200) {
#warning 检测实名认证
            [self checkSimplecertification];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
#pragma mark-发送---实名认证
-(void)checkSimplecertification
{
    self.urlString = [NSString stringWithFormat:@"%@/simplecertification/Authenticationstatus",kUrl];
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid]
                  };
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        //    NSString *message = [info.userInfo objectForKey:@"message"];
        
        NSInteger date = [[responseObject objectForKey:@"date"]integerValue];
        if (date == 5) {
            [UserDefaultsHelper saveType:@"" value:@"1"];
        }else  if (date == 2) {
            [UserDefaultsHelper saveType:@"" value:@"2"];
        }
        
        if (date == 2||date == 5||date == 9) {
            MyShopVC *vc = [[MyShopVC alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"实名认证后才可以创建店铺,请进行实名认证"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark-点击
-(void)ShareView:(ShareView *)ShareView withInterget:(NSInteger)interger
{
    if (interger == 0) {
        XLog(@"0");
        [self shareWebPageToPlatformType:UMSocialPlatformType_Sina];
    }else if (interger == 1) {
        [self shareWebPageToPlatformType:UMSocialPlatformType_QQ];
    }else if (interger == 2) {
        [self shareWebPageToPlatformType:UMSocialPlatformType_Qzone];
    }else if (interger == 3) {
        [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession];
    }else if (interger == 4) {
        //UMSocialPlatformType_DingDing
        //UMSocialPlatformType_WechatTimeLine
        [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine];
    }else if (interger == 5) {
//        [self shareWebPageToPlatformType:UMSocialPlatformType_UserDefine_Begin+2];
        //分享到剪切板
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"链接已复制到剪贴板"];
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = [NSString stringWithFormat:@"http://www.qichangkeji.vip/gongzhonghaoWeb/page/shareSj.html"];
        //XLog(@"interger");
    }
}
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
//    NSString* thumbURL =  @"http://www.qichangkeji.vip/upload/img/e2295b16-1256-474e-8df6-47545a7f8c38.png";
    UIImage *image = [UIImage imageNamed:@"BusinessMarket"];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"商集APP" descr:@"线上的商务拓展合作信息整合平台" thumImage:image];
    //设置网页地址
    shareObject.webpageUrl = @"http://www.qichangkeji.vip/gongzhonghaoWeb/page/shareSj.html";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        XLog(@"platformType:%ld",platformType);
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            if (platformType == 4||platformType == 5) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"暂未安装QQ,不能通过QQ分享"];
            }else if (platformType == 1) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"暂未安装微信,不能通过微信分享"];
            }else if (platformType == 2) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"暂未安装微信,不能分享到朋友圈"];
            }
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}


@end
